package com.comtime.usercenter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.comtime.greendaodemo.DeviceInfo;
import com.comtime.greendaoutils.DataBaseUtil;
import com.comtime.login.LoginActivity;
import com.comtime.service.MyService;
import com.comtime.smartbox.Activity_0;
import com.comtime.smartbox.BaseActivity;
import com.comtime.smartbox.HBApplication;
import com.comtime.smartbox.MainActivity;
import com.comtime.smartkilimanjaro.R;
import com.comtime.swdevice.SWDeviceScanManager;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.utils.ToastUtils;
import com.comtime.utils.Util;
import com.comtime.view.ActionSheet;
import com.comtime.view.EditDialog;
import com.comtime.view.EditDialog.OnEditClickListener;
import com.comtime.view.MyDialog;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;
import com.comyou.roundimageview.RoundedImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class UserInfoActivity extends BaseActivity {
	public static String Extra_NeedAddFirstUser = UserInfoActivity.class.getName()+"_Extra_NeedAddFirstUser";


	RoundedImageView image_photo;
	TextView tv_phonenum;
	EditText edit_name;
	RelativeLayout relate_account;
	MySharedPreferences mySharedPreferences;
	DataBaseUtil dataBaseUtil;
	HBApplication application;
	SWDeviceScanManager scanManager;
	private boolean needAddFirstUser;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_userinfo);
		mySharedPreferences = MySharedPreferences.getInstance(this);
		application = (HBApplication) getApplication();
		dataBaseUtil = DataBaseUtil.getInstance(this);

		image_photo = (RoundedImageView) findViewById(R.id.image_photo);
		tv_phonenum = (TextView) findViewById(R.id.tv_phonenum);
		tv_phonenum.setText(mySharedPreferences.getPhoneNum());
		relate_account = (RelativeLayout) findViewById(R.id.relate_account);
		edit_name = (EditText) findViewById(R.id.edit_name);
		edit_name.setText(mySharedPreferences.getUserName());
		initFile();
		regist();

		needAddFirstUser = getIntent().getBooleanExtra(Extra_NeedAddFirstUser, false);
		if (needAddFirstUser) {
			showEditDialog(getText(R.string.input_admin_pwd).toString());
		}
		mySharedPreferences.savaBoolen("needAddFirstUser",needAddFirstUser);
//		 if(!application.swDevicesList.get(0).checkUserOk){
//			 showEditDialog(getText(R.string.input_admin_pwd).toString());
//		 }
	}
	void regist() {
		IntentFilter filter=new IntentFilter(
				MyService.ACTION_CHECKADMINEPWD_RESULT);
		filter.addAction(MyService.ACTION_DISCONNECTED);
		registerReceiver(receiver, filter);
	}
	public void backAction(View v) {
		this.finish();
		overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
	}

	public void authAction(View v){
		Intent intent = new Intent(this, AuthActivity.class);
		startActivity(intent);
	}

	/**
	 * 修改密码
	 *
	 * @param v
	 */
	public void UpdateAction(View v) {
		Intent intent = new Intent(this, ChangePasswordActivity.class);
		startActivity(intent);
	}

	/**
	 * 用户账户管理
	 *
	 * @param v
	 */
	public void UserAccountAction(View v) {

		if(MyConfig.canUse&&application.swDevicesList.get(0).isConnected()){
			showEditDialog(getText(R.string.input_admin_pwd).toString());
		}else{
			showToast(getText(R.string.device_dis_connect).toString());
		}


	}

	/**
	 * 退出登录
	 *
	 * @param v
	 */
	public void ExitAction(View v) {
		showCanUseDialog(getString(R.string.exit_sure).toString());
	}

	/**
	 * 头像
	 *
	 * @param v
	 */
	public void PhotoAction(View v) {
		// showActionSheet();
	}

	OnClickListener itemsOnClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_top:
				camera();
				actionSheet.dismiss();
				break;
			case R.id.btn_center:
				gallery();
				actionSheet.dismiss();
				break;
			case R.id.btn_down:
				actionSheet.dismiss();
				break;
			default:
				break;
			}
		}
	};
	String action = "";
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			action = intent.getAction();
            //RZC 判断管理员密码结果返回，之前都是通过设备返回值来判定，现在需要改成在服务器返回值判定
			if (action.equals(MyService.ACTION_CHECKADMINEPWD_RESULT)) {
				int num = intent.getIntExtra(MyService.VALUE_INFO, 0);
				if (num == 0) {
					handler.sendEmptyMessage(0);
				} else {
					handler.sendEmptyMessage(1);
				}
			}else if(action.equals(MyService.ACTION_DISCONNECTED)){
				handler.sendEmptyMessage(2);
			}

		}
	};

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				showToast(getText(R.string.input_admin_pwd_fail).toString());

				break;
			case 1:
				/*Intent intent = new Intent(UserInfoActivity.this, MyUserActivity.class);
				startActivity(intent);*/
				 Intent intent = new Intent(UserInfoActivity.this, AccountManagerActivity.class);
				 startActivity(intent);
				break;
			case 2:
				showToast(getText(R.string.device_dis_connect).toString());
				if(editDialog!=null){
					editDialog.cancel();
				}
				break;
			default:
				break;
			}

		};
	};

	/**************** photo *******************/
	ActionSheet actionSheet;
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private File tempFile, tempFile2;
	private String PHOTO_FILE_PATH = getPath(Environment
			.getExternalStorageDirectory() + "/" + "SmartECH/");

	boolean isNULL = true;

	void initFile() {
		int time = (int) (System.currentTimeMillis() / 100000);
		tempFile = getFile(PHOTO_FILE_PATH + "/" + time + ".jpg");
		tempFile2 = getFile(PHOTO_FILE_PATH + "/" + time + "two" + ".jpg");
	}

	void showActionSheet() {
		actionSheet = new ActionSheet(this, itemsOnClick, getString(
				R.string.camara).toString(), getString(R.string.photo_phone)
				.toString(), getString(R.string.cancel).toString());
		// 显示窗口
		actionSheet.showAtLocation(findViewById(R.id.activity_userinfo),
				Gravity.BOTTOM, 0, 0); // 设置layout在PopupWindow中显示的位置
	}

	/**
	 * 从手机相册中获取
	 */
	private void gallery() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
	}

	/**
	 * 拍照
	 */
	private void camera() {
		// 判断存储卡是否可以用，可用进行存储
		if (Util.hasSdcard()) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 调用照相机
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile2));
			startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
		}
	}

	String headURLString = "";
	boolean header_flag = false;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 相册选取
		if (requestCode == PHOTO_REQUEST_GALLERY && data != null) {

			crop(data.getData(), Uri.fromFile(tempFile));
		}
		// 照相机选取
		else if (requestCode == PHOTO_REQUEST_CAMERA
				&& resultCode == Activity.RESULT_OK) {
			// 这里拍摄图片和截取后的图片文件都写入了同一个文件，photo.jpg
			crop(Uri.fromFile(tempFile2), Uri.fromFile(tempFile));

		}
		// 返回截取的图片
		else if (requestCode == PHOTO_REQUEST_CUT && data != null) {
			// 裁切大图使用Uri
			Bitmap bitmap = decodeUriAsBitmap(Uri.fromFile(tempFile));//
			Log.i("tag", "bitmap:是否为空：" + (bitmap == null) + "  tempFile:"
					+ tempFile);
			if (bitmap != null) {
				image_photo.setImageBitmap(bitmap);
				header_flag = true;
			}

		} else {

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 裁切图片 uri为选中图片返回的Uri cutImgUri为把截取图片写入sd卡的Uri
	 */
	private void crop(Uri uri, Uri cutImgUri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 500);
		intent.putExtra("outputY", 500);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", false);// true:不返回uri，false：返回uri
		intent.putExtra(MediaStore.EXTRA_OUTPUT, cutImgUri);// 写入截取的图片
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	/**
	 * uri转换为bitmap
	 *
	 * @param uri
	 * @return
	 */
	public Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(this.getContentResolver()
					.openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

	/**
	 * 创建文件夹
	 *
	 * @param path
	 * @return
	 */
	private File getFile(String path) {
		File f = new File(path);
		if (!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return f;
	}

	private static String getPath(String path) {
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		return f.getAbsolutePath();
	}

	MyDialog myDialog;

	private void showCanUseDialog(String str) {

		if (myDialog != null) {
			myDialog.cancel();
		}
		myDialog = new MyDialog(UserInfoActivity.this);
		myDialog.setContent(str);
		myDialog.setLeftButtonText(getText(R.string.cancel));
		myDialog.setRightButtonText(getText(R.string.ok));
		myDialog.setCancelable(false);
		myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				myDialog.dismiss();
			}
		});
		myDialog.getRighrButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				myDialog.dismiss();
				mySharedPreferences.saveIsLogined(false);

				Intent intent = new Intent(UserInfoActivity.this,
						LoginActivity.class);
				startActivity(intent);

				Intent exitIntent = new Intent(MainActivity.EXIT);
				sendBroadcast(exitIntent);
				finish();
			}
		});
		myDialog.show();
	}
	EditDialog editDialog=null;
	private void showEditDialog(String str) {
		if(editDialog!=null){
			editDialog.cancel();
		}
		editDialog = new EditDialog(UserInfoActivity.this,
				new OnEditClickListener() {

					@Override
					public void onOkFeedBack(String str) {
						if (str.equals("")) {
							showToast(getText(R.string.input_admin_pwd)
									.toString());
						}else if(str.length()==6){
							// 发送密码
							application.swDevicesList.get(0)
									.sendCheckAdministrator(str);
                            //TODO:保存管理员密码，远程添加用户需要用到
						} else {
							// 密码有误
							showToast(getText(R.string.input_admin_pwd_length_fail)
									.toString());
						}
					}

					@Override
					public void onCancelFeedBack() {
						if(needAddFirstUser){
							application.swDevicesList.get(0).disconnect();
							mySharedPreferences.saveBluAdress("");
						}



					}
				});
		editDialog.setTitle(str);
		editDialog.setLeftButtonText(getText(R.string.cancel));
		editDialog.setRightButtonText(getText(R.string.ok));
		editDialog.setCancelable(false);

		editDialog.show();
	}



	/**
	 * 自定义提示语
	 *
	 * @param str
	 */
	Toast toast = null;

	void showToast(String str) {
		if (toast != null) {
			toast.cancel();
		}
		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.inflate(R.layout.toastshow, null);
		TextView textView = (TextView) view.findViewById(R.id.toastshow);
		textView.setText(str);
		Toast toast = new Toast(this);
		double d = getResources().getDisplayMetrics().density;
		toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(view);
		toast.show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
		if (!edit_name.getText().toString()
				.equals(mySharedPreferences.getUserName())) {
			mySharedPreferences.saveUserName(edit_name.getText().toString());
		}

	}
}
